package com.cn.aam.checaiduo.ui.homepage.fragment;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.cn.aam.checaiduo.AppData;
import com.cn.aam.checaiduo.BuildConfig;
import com.cn.aam.checaiduo.Const;
import com.cn.aam.checaiduo.R;
import com.cn.aam.checaiduo.backend.RetrofitHome;
import com.cn.aam.checaiduo.backend.observer.OnRequestListener;
import com.cn.aam.checaiduo.backend.observer.OnRequestV2Listener;
import com.cn.aam.checaiduo.backend.rx.RxSchedulers;
import com.cn.aam.checaiduo.base.BaseFragment;
import com.cn.aam.checaiduo.bean.AvatarB;
import com.cn.aam.checaiduo.bean.base.BaseResponseB;
import com.cn.aam.checaiduo.bean.base.NormalResponseB;
import com.cn.aam.checaiduo.bean.other.BasicUserInfoB;
import com.cn.aam.checaiduo.center.CustomDialogCenter;
import com.cn.aam.checaiduo.center.UserCenter;
import com.cn.aam.checaiduo.minterface.OnTabSelectedListener;
import com.cn.aam.checaiduo.ui.arouter.UIRouter;
import com.cn.aam.checaiduo.ui.arouter.section.RouterMore;
import com.cn.aam.checaiduo.ui.homepage.MainActivity;
import com.cn.aam.checaiduo.ui.me.PlatformIntroduceActivity;
import com.cn.aam.checaiduo.utils.FileUtils;
import com.cn.aam.checaiduo.utils.MyViewsUtils;
import com.cn.aam.checaiduo.widget.WMToast;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.weimu.library.ImagePicker;
import com.weimu.library.view.ImageSelectorActivity;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.functions.Consumer;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static android.app.Activity.RESULT_OK;


/**
 * @author 微木森林
 * @time 2017/6/9 下午2:12
 * @description 更多
 * @remark
 */
public class OtherMoreFragment extends BaseFragment implements OnTabSelectedListener {

    @BindView(R.id.iv_avatar)
    CircleImageView ivAvatar;
    @BindView(R.id.tv_mobile)
    TextView meTvMobile;

    @BindView(R.id.btn_un_auth)
    TextView btnUnAuth;
    @BindView(R.id.tv_activity_number)
    TextView tvActivityNumber;


    private boolean isAuthed = false;//是否已经实名认证

    private BasicUserInfoB basicUserInfo;

    public static OtherMoreFragment newInstance() {
        OtherMoreFragment intance = new OtherMoreFragment();
        return intance;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_other;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        MyViewsUtils.hideAllViews(ivAvatar, meTvMobile, btnUnAuth, tvActivityNumber);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) getUserInfo();
    }


    /**
     * 获取用户信息
     */
    private void getUserInfo() {
        RetrofitHome.getInstance().getInternalApi()
                .getBasicUserInfo(AppData.getToken())
                .compose(RxSchedulers.<NormalResponseB<BasicUserInfoB>>toMain())
                .subscribe(new OnRequestV2Listener<BasicUserInfoB>(mActivity) {
                    @Override
                    protected boolean isShowProgressBar() {
                        return false;
                    }

                    @Override
                    public void onNext(NormalResponseB<BasicUserInfoB> value) {
                        super.onNext(value);
                        if (value.getIsLogged() != Const.STATE_LOGIN) {
                            goLogin();
                            return;
                        }
                        basicUserInfo = value.getData();
                        renderViews(value.getData());
                    }
                });

    }

    private void renderViews(BasicUserInfoB data) {
        //mobile
        meTvMobile.setText(data.getMobile());
        //auth
        if (!"1".equals(data.getAuth_status())) {
            btnUnAuth.setText("未认证");
            isAuthed = false;
        } else {
            btnUnAuth.setText("已认证");
            isAuthed = true;
        }
        //avatar
        Glide.with(mActivity).load(data.getHeadimgurl()).asBitmap().placeholder(R.drawable.ic_avatar_default).into(ivAvatar);
        //activity number
        tvActivityNumber.setText(data.getActivity_number());

        //show
        MyViewsUtils.showAllViewOneByOne((long) 100, ivAvatar, meTvMobile, btnUnAuth);
    }


    /**
     * @description 实名认证
     */
    @OnClick(R.id.block_auth)
    public void onClickAuth() {
        if (MyViewsUtils.isFastDoubleClick()) return;
        if (isAuthed)
            UIRouter.getInstance().getMore().openAuthResultPage(mActivity, basicUserInfo);
        else
            UIRouter.getInstance().openPage(mActivity, UIRouter.MORE.AUTH);
    }

    /**
     * @description 任务中心
     */
    @OnClick(R.id.block_mission_center)
    public void onClickMissionCenter() {
        if (MyViewsUtils.isFastDoubleClick()) return;
        UIRouter.getInstance().openPage(mActivity, UIRouter.MORE.TASK_CENTER);
    }


    /**
     * @description 活动中心
     */
    @OnClick(R.id.block_activity_center)
    public void onClickActivityCenter() {
        if (MyViewsUtils.isFastDoubleClick()) return;
        startActivity(PlatformIntroduceActivity.newInstance(mActivity, PlatformIntroduceActivity.FLAG_ACTIVITY));
    }

    /**
     * @description 帮助中心
     */
    @OnClick(R.id.block_help_center)
    public void onClickHelpCenter() {
        if (MyViewsUtils.isFastDoubleClick()) return;
        UIRouter.getInstance().openPage(mActivity, UIRouter.MORE.HELP_CENTER);
    }

    /**
     * @description 系统设置
     */
    @OnClick(R.id.block_setting)
    public void onClickSetting() {
        UIRouter.getInstance().openPage(mActivity, UIRouter.MORE.SETTING);
    }

    /**
     * @description 关于我们
     */
    @OnClick(R.id.block_about_us)
    public void onClickAboutUs() {
        if (MyViewsUtils.isFastDoubleClick()) return;
        UIRouter.getInstance().getWeb().openRedToolBarPage(mActivity, BuildConfig.HOST + "Wap/Usercenter/aboutus.html", "关于我们");
    }

    /**
     * @description 退出登录
     */
    @OnClick(R.id.tv_logout)
    void onClickLogout() {
        if (MyViewsUtils.isFastDoubleClick()) return;
        RetrofitHome.getInstance()
                .getUserApi()
                .logout()
                .compose(RxSchedulers.<BaseResponseB>toMain())
                .subscribe(new OnRequestListener<BaseResponseB>(mActivity) {
                    @Override
                    public void onNext(BaseResponseB value) {
                        super.onNext(value);
                        if (value.getCode() == Const.REQUEST_FAILED) return;
                        //out
                        UserCenter.getInstance().logOut();

                        ((MainActivity) mActivity).setCurrentFragment(0);
                    }
                });
    }

    /**
     * 修改头像
     */
    @OnClick(R.id.iv_avatar)
    public void onClickChangeAvatar() {
        if (MyViewsUtils.isFastDoubleClick()) return;
        new RxPermissions(mActivity)
                .request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean granted) throws Exception {
                        if (granted)
                            selectorImage();
                        else
                            showPermissionDialog();
                    }
                });
    }


    private void selectorImage() {
        //修改头像功能
        ImagePicker.getInstance().pickAvatar(mActivity);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ImageSelectorActivity.REQUEST_IMAGE://头像选择
                if (resultCode == RESULT_OK) doChangeAvatar(data);
                break;

        }
    }

    /**
     * 修改头像
     *
     * @param data
     */
    private void doChangeAvatar(Intent data) {
        final ArrayList<String> pics = data.getStringArrayListExtra(ImageSelectorActivity.REQUEST_OUTPUT);
        if (pics == null || pics.size() <= 0) {
            WMToast.normal("头像选择出问题，请重新选择");
            return;
        }

        String avatarPath = pics.get(0);
        //压缩
        Bitmap bitmap = BitmapFactory.decodeFile(avatarPath);
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 150, 150, true);
        File pic = FileUtils.saveBitmapFile(scaledBitmap, avatarPath);

        //传入multipartbody
        MultipartBody.Part avatar = MultipartBody.Part.createFormData("avatar", pic.getName(), RequestBody.create(MultipartBody.FORM, pic));
        MultipartBody.Part token = MultipartBody.Part.createFormData("token", AppData.getToken());

        RetrofitHome.getInstance().getInternalApi()
                .postAvatar(token, avatar)
                .compose(RxSchedulers.<NormalResponseB<AvatarB>>toMain())
                .subscribe(new OnRequestV2Listener<AvatarB>(mActivity) {
                    @Override
                    public void onNext(NormalResponseB<AvatarB> value) {
                        super.onNext(value);
                        if (value.getIsLogged() == 0) {
                            goLogin();
                            return;
                        }
                        if (value.getCode() == Const.REQUEST_SUCCESS) {
                            WMToast.normal("更新头像成功");
                            String avatar = value.getData().getHeadimg_url();
                            Glide.with(mActivity).load(avatar).asBitmap().placeholder(R.drawable.ic_avatar_default).into(ivAvatar);
                        }
                    }
                });


    }

    private void showPermissionDialog() {
        CustomDialogCenter.getInstance().showPermissionTipDialog(mActivity, "没有相关权限，APP将无法正常访问图库!");
    }

    @Override
    public void onTabReSelected() {
        MyViewsUtils.hideAllViews(ivAvatar, meTvMobile, btnUnAuth, tvActivityNumber);
        getUserInfo();
    }
}
